package com.ag.oa.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CustomUtil {

    public static String getUUID32(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    /**
     * 判断一个字符是否是中文
     * */
    public static boolean isChineseCharacter(char c) {

        return c >= 0x4E00 && c <= 0x9FA5; // 根据字节码判断
    }

    /**
     * 判断字符串是否合法手机号
     */
    public static boolean isMobileNumber(String mobile) {

        if (mobile==null || mobile.trim().length()==0) {
            return false;
        }

        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /**
     * 判断是否测试体验版的请求 url
     */
    public static boolean isTestRequestEnv(HttpServletRequest request) {

        boolean isTestEnv = false;
        String servletPath = request.getServletPath();
        if (servletPath.startsWith("/test")) {
            isTestEnv = true;
        }
        return isTestEnv;
    }

    /**
     * 日期格式化
     */
    public static String format(Date date, String pattern) {

        if (date==null) {
            return "";
        }

        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * 判断字符串是否为空
     */
    public static boolean strNotEmpty(String str) {

        if (str!=null && str.trim().length()!=0 && !str.equals("null")) {
            return true;
        }
        return false;
    }

    /**
     * 字符串转拼音
     */
    public static Map<String, String> changeChinese2Pinyin(String chinese) throws
            BadHanyuPinyinOutputFormatCombination {

        Map<String, String> pinyin = new HashMap<>();

        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);

        StringBuffer fullPinyin = new StringBuffer();
        StringBuffer simplePinyin = new StringBuffer();
        StringBuffer firstPinyin = new StringBuffer();

        char[] chineseChar = chinese.toCharArray();
        for (int i = 0; i < chineseChar.length; i++) {
            String[] str = null;
            try {
                str = PinyinHelper.toHanyuPinyinStringArray(chineseChar[i], format);
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }

            if (str != null) {
                fullPinyin = fullPinyin.append(str[0].toString());
                simplePinyin = simplePinyin.append(str[0].charAt(0));
            }

            if (str == null) {
                String regex = "^[0-9]*[a-zA-Z]*+$";
                Pattern pattern = Pattern.compile(regex);
                Matcher m = pattern.matcher(String.valueOf(chineseChar[i]));
                if (m.find()) {
                    fullPinyin = fullPinyin.append(chineseChar[i]);
                    simplePinyin = simplePinyin.append(chineseChar[i]);
                }
            }
        }

        String[] name = PinyinHelper.toHanyuPinyinStringArray(chineseChar[0], format);
        firstPinyin=firstPinyin.append(name[0].charAt(0));
        pinyin.put("fullPinyin", fullPinyin.toString());
        pinyin.put("simplePinyin", simplePinyin.toString().toUpperCase());
        pinyin.put("groupPinyin", firstPinyin.toString().toUpperCase());
        return pinyin;
    }

    /**
     * 上传图片到本地服务器
     */
    public static void uploadPicture2LocalServer(HttpServletRequest request, Integer userId
            , String filePath) throws IOException {

        // 创建一个通用的多部分解析器.
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        commonsMultipartResolver.setDefaultEncoding("utf-8");  //设置编码

        // 判断 request 是否有文件上传, 即多部分请求...
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;  //转换成多部分request
            Iterator<String> iterator = multiRequest.getFileNames(); // 获取所有的文件名

            while (iterator.hasNext()) {
                String name = iterator.next();  // input 标签中的 name 属性名称 (voucherImg1)
                MultipartFile tempFile = multiRequest.getFile(name);  // 根据 name 获取上传的文件...

                // 文件不为空
                if (!tempFile.isEmpty()) {
                    // 新生成的文件名
                    String fileName = userId +"_"+ format(Calendar.getInstance().getTime()
                            , "yyyyMMdd") +"_"+ tempFile.getOriginalFilename();

                    // 上传的文件
                    File file = new File(filePath, fileName);
                    tempFile.transferTo(file);  // 文件上传
                }
            }
        }
    }

}
